package br.com.hd.dao;

import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import br.com.hd.entity.Chamado;
import br.com.hd.util.HibernateUtility;

public class ChamadoDAO extends DAO {

	private static ChamadoDAO instance;

	private ChamadoDAO() {
	}

	public static ChamadoDAO getInstance() {
		if (instance == null) {
			instance = new ChamadoDAO();
		}
		return instance;
	}

	@SuppressWarnings("unchecked")
	public List<Chamado> pesquisar(Chamado chamado)
			throws NoSuchAlgorithmException {
		HibernateUtility.beginTransaction();
		Criteria c = HibernateUtility.getSession()
				.createCriteria(Chamado.class);
		if (chamado.getDepartamento().getCodigo() != 0) {
			c.add(Restrictions.eq("departamento", chamado.getDepartamento()));
		}
		if (chamado.getStatus().getCodigo() != 0) {
			c.add(Restrictions.eq("status", chamado.getStatus()));
		}
		c.add(Restrictions.eq("nivel", chamado.getResponsavel().getNivel()));
		// HibernateUtility.commitTransaction();
		return c.list();
	}
	
	public void updateNoMessage(Object objeto) {
		try {
			HibernateUtility.getSession().clear();
			HibernateUtility.beginTransaction();
			HibernateUtility.getSession().update(objeto);
			HibernateUtility.commitTransaction();
		} catch (Exception e) {
			HibernateUtility.rollbackTransaction();
			FacesMessage message = new FacesMessage(
					FacesMessage.SEVERITY_ERROR,
					"Erro ao comunicar com o servidor!",
					"Erro ao comunicar com o servidor!");
			FacesContext.getCurrentInstance().addMessage("", message);
		}
	}


}